// 引入接口文件
import {
  getDetail,
  update,
  create,
  labelQueryList,
  areAddressGet,
  houseListGet,
  gethouseTypeList,
  queryAccount,
  queryInfo,
  regionArea,
  getProduct ,
  getAccountDetail,
  getPayCodeList
} from './productEditServ.js'

// 对象和JSON字符串互转
import { parse } from 'qs'
// 弹出消息框
import { message } from 'antd'
// 日期处理对象
import moment from 'moment'
/*isEmpty 对象是否为空
 *isArray 对象是否数组
 *cloneDeep 对象深拷贝
 */
import { isEmpty, isArray, cloneDeep, merge, pick } from 'lodash'
// 引入路由对象
import { hashHistory } from 'dva/router'
import AppBus from '../../../../utils/bus'
import { makeAddress ,download} from "utils/util"
let productTypeLabelMap = {  1: '详细房号', 2: '车位位置', 3: '商铺位置',4:'商品名称',5:'商品名称',6:'商品名称',7:'商品名称'  }
// 初始默认状态
const defultState = {
  xxx: '1',
  loading: false,
  btnLoading: false,
  id: '',
  parentProductId: '',
  pageType: 'detail',
  sellType: '2',
  isClone: false,
  accountList: [],//根据项目查找对公账户
  allAddress: [],
  houseList: [],
  detailInfo: {},
  formData: {
    'projectId': '',
    'projectName': '',
    'houseTypeName': ['','',''],
    'detail': '',
    'area': '',
    'productType': '',
    'propertyType': '',
    'seckillPrice': '',
    'originalPrice': '',
    'securityMoney': '',
    'earnestMoney': '',
    'squarePrice': '',
    'orientation': '',
    'imageUrls': [],
    'tags': [],
    'productLabel': '详细房号：',
    'city': '',
    'province': '',
    'productId': '',
    'productBankAccountId': '',
    'enrollType':'',
    'promotionDetail':'',//商品描述
    'productDesc':'',//商品介绍
    "color": "",
    "other": "",
    "power": "",
    "producingArea": "",
    "size": "",
    "volume": "",
    "weight": "",
    "bankAccount":'',
    accountName:'',
    show:false,
    needEnroll:''
  },
  tagInputValue: '',
  tagInputVisible: false,
  imageUrls: [],
  tagsList: [],//所有标签
  houseTypeList: [],//户型列表
  tags: [],//已选中标签
  accountType:1,
  modalObj: {
    project: {
    visible: false,
    },
    productList: {
      visible: false,
    },
    productList1: {
      visible: false,
    },
    accountList:{
      visible: false,
    }
  },
  standards:{
    volume:'',
    weight:'',
    power:'',
    size:'',
    color:'',
    producingArea:'',
    other:''
  },
  selectOption: {
    value: '', // 选择的默认1
    des: '', // 选择的默认
  },
  medias:[],
  teamsOptions:[
    {value:'volume', label:'容量'},
    {value:'weight', label:'重量'},
    {value:'power', label:'功率'},
    {value:'size', label:'体积'},
    {value:'color', label:'颜色'},
    {value:'producingArea', label:'产地'},
    {value:'other', label:'其他'},
  ],
  biz:{
    queryForm:{
      province: null,
      city:null,
      pageSize: 10,
      pageNo:1,
      name:null
    },
    selectedRowKeys:[]
  },
  biz1:{
    queryForm:{
      pageSize: 10,
      pageNo:1,
      regionId:'',
      provinceCode:'',
      cityCode:'',
      productBankAccountId:''
    },
    selectedRowKeys:[],
    selectedRows:[]
  },
  area1:[],
  products:[],
  areaList:[],
  payCodeList:[],//商户支付号列表
  isAll:false
}

// 声明module
const tmpModule = {
  // namespace: 'secondKillingSetting',
  // 默认状态
  state: cloneDeep(defultState),
  // 入口函数(先执行)
  subscriptions: {
    setup({ dispatch, history }) {
      history.listen(({ pathname, query }) => {
        // 页面路由匹配时执行
        if ('' + tmpModule.pathname === '' + pathname) {
          dispatch({ type: 'updateStore', payload: { ...cloneDeep(defultState), ...query } })//每次进去页面先重置状态
          dispatch({type:'getPayCodeList',payload:{}});
          console.log('subscriptions', pathname, query)
          if (query.pageType == 'edit') {
            if(query.detailType=='good'){
              dispatch({
                type: 'getDetail',
                payload: {
                  productId:query.id,
                  id: query.id,
                  isClone: query.isClone||false,
                }
              })
            }else{
              dispatch({
                type: 'queryInfo',
                payload: {
                  pageType: query.pageType,
                  id: query.id,
                  isClone: query.isClone||false,
                }
              })
            }
          } else {
            dispatch({
              type: 'updateStore',
              payload: {
                pageType: query.pageType,
                id: query.id,
                isClone: query.isClone||false,
              }
            })
          }
          dispatch({ type: 'gethouseTypeList', payload: {} })
          dispatch({ type: 'getArea', payload: {} })
          dispatch({ type: 'getLabelQueryList', payload: {} })
          dispatch({ type: 'queryAccount', payload: { id: query.id} })
          dispatch({ type: 'regionArea', payload: {} })
        } // end if
      }) // end listen
    },
  },

  // 方法列表
  effects: {
    *getPayCodeList({payload},{put,call,select}){
      try{
        const { rows, success } = yield call(getPayCodeList,{});
        console.log(rows);
        if(success){
          if(rows){
            rows.map((item,i)=>{
              item.key = i
            })
            console.log('rows:',rows)
            yield put({ type: 'updateStore', payload: { payCodeList: rows } });
          }
        }
      }catch(e){

      }
    },
    *regionArea({payload},{put,call,select}){
          try {
            let {biz1,areaList}=yield select(state => state[tmpModule.namespace])
              const {success,data}=yield call(regionArea)
              if(success){
                if(biz1.queryForm.regionId){
                  data.map((item,index)=>{
                    console.log(item)
                    if(item.value==biz1.queryForm.regionId){
                      areaList = makeAddress(item.children,2)
                    }
                  })
                }
                yield put({type:'updateStore',payload:{area1:data,areaList}})
                yield put({type:'getProduct',payload:{}})
              }
          } catch (error) {
            
          }
			},
		*getProduct({payload},{put,call,select}){
			let {products,biz1} = yield select(state => state[tmpModule.namespace])
			if(biz1.queryForm.getProduct){
				const { data, success } = yield call(getProduct,{cityCode:biz1.queryForm.cityCode});
				if(success){
					products=data
					yield put({ type: 'updateStore',payload:{products}})
				}
			}
			
		},
    
    //非房产
     *getDetail({payload},{put,call,select}){
      let { id, detailInfo, formData, tags, imageUrls,sellType,selectOption,teamsOptions,biz} = yield select(state => state[tmpModule.namespace])
      const { success, msg, data } = yield call(getDetail, payload)
      if (success) {
        for(let x in teamsOptions){
          for(let y in data){
            if(teamsOptions[x].value==y){
              selectOption.value=y
              selectOption.des=data[y]
            }
          }
        }
        detailInfo = data || {}
        formData = data || {}
        formData.projectId = formData.parentProductId;
        tags = data.tags || []
        formData.detail=formData.name
        if(data.catalogId=='9004'){
          formData.productType='4'
        }else if(data.catalogId=='9005'){
          formData.productType='5'
        }else if(data.catalogId=='9006'){
          formData.productType='6'
        }else if(data.catalogId=='9009'){
          formData.productType='7'
        }
        if(formData.medias){
         imageUrls = formData.medias.map(item => item.fileUrl)
        }
        formData.productDesc=formData.description
        console.log(formData.productDesc)
        formData.productLabel = productTypeLabelMap[formData.productType] || null
        
        biz.queryForm={
          ...biz.queryForm,
          province:data.province,
          city:data.city,
          name:data.parentProductName
        } 
        biz.selectedRowKeys[0]=data.parentProductId
        
        // yield put ({type: `houseListGet`, payload: {province: data.province, city:data.city,pageSize: 10000}})
        yield put ({type: `queryAccount`, payload: {id:formData.projectId}})
        // const { success, rows } = yield call(houseListGet, { province: data.province, city: data.city, pageSize: 10000 });
        // if (success) {
        //   yield put({ type: 'updateStore', payload: { houseList: rows || [] } })
        // }
      }
      yield put({
        type: 'updateStore',
        payload: {
          detailInfo,
          formData,
          tags,
          imageUrls,
          ...payload,
          biz
        }
      })
    },
    // 查询记录  详情
    * queryInfo({ payload }, { put, call, select }) {
      let { id, detailInfo, formData, tags, imageUrls,sellType,teamsOptions,selectOption,biz,biz1} = yield select(state => state[tmpModule.namespace])
      const { success, msg, data } = yield call(queryInfo, { id: payload.id || id, })
      let t1 = moment()
      if (success) {
          for(let x in teamsOptions){
            for(let y in data){
              if(teamsOptions[x].value==y){
                selectOption.value=y
                selectOption.des=data[y]
              }
            }
          }
        detailInfo = data || {}
        formData = data || {}
        formData.projectId = formData.projectId;
        tags = data.tags || []
        imageUrls = data.imageUrls || []
        formData.productLabel = productTypeLabelMap[formData.productType] || null
        if(!formData.houseTypeName){
          formData.houseTypeName=['','','',''];//x室x厅x卫
        }else{
          formData.houseTypeName=(formData.houseTypeName||'').split(/[室|厅|厨|卫]/);//x室x厅x卫
          if(formData.houseTypeName>4){
            formData.houseTypeName.splice(2,1)//去掉厨房
          }
        }
        // yield put ({type: `houseListGet`, payload: {province: data.province, city:data.city,pageSize: 10000}})
        yield put ({type: `queryAccount`, payload: {formData, id: formData.projectId,}})
        // const { success, rows } = yield call(houseListGet, { province: data.province, city: data.city, pageSize: 10000 });
        // if (success) {
        //   yield put({ type: 'updateStore', payload: { houseList: rows || [] } })
        // }
        console.log(biz)
        biz.queryForm={
            ...biz.queryForm,
            province:data.province,
            city:data.city,
            name:data.projectName
          } 
          biz.selectedRowKeys[0]=data.projectId
          biz1.queryForm={
            ...biz1.queryForm,
            productBankAccountId:data.productBankAccountId,
          } 
      }
      
     
      yield put({
        type: 'updateStore',
        payload: {
          detailInfo,
          formData,
          tags,
          accountType:formData.productBankAccountId?2:1,
          imageUrls,
          ...payload,
          show:moment(formData.startTime).isBefore(t1) && formData.status!=5,
          biz,
          biz1
        }
      })
      if(data.productBankAccountId){
        yield put({
          type:'getAccountDetail',
          payload:{
            id:data.productBankAccountId
          }
        })
      }
    },
    *getAccountDetail({payload},{put,call,select}){
      let {params,biz1,formData}=yield select(state => state[tmpModule.namespace])
      let {data,success}=yield call(getAccountDetail,payload)
      biz1.queryForm={
        ...biz1.queryForm,
        provinceCode:data.province,
        cityCode:data.city,
        regionId:data.regionId,
        productId:data.productId,
        province:data.province,
        city:data.city,
      } 
      formData={
        ...formData,
        bankAccount:data.bankAccount,
        accountName:data.accountName,

      }
      biz1.selectedRowKeys[0]=data.productBankAccountId
      biz1.selectedRows[0]=data
      params={
        provinceCode:data.province,
        cityCode:data.city,
        regionId:data.regionId
      }
      if(success){
        params.regionId=data.regionId
        yield put({
          type:'updateStore',payload:{ params, biz1,formData}
        })
        yield put({ type: 'regionArea', payload: {} })
      }
    },

    // 修改
    * update({ payload }, { put, select, call }) {
      let { id, formData, tags, imageUrls ,standards,teamsOptions,selectOption,accountType} = yield select(state => state[tmpModule.namespace])
      for(let i in standards){
        if(selectOption.value==i){
          standards[i]=selectOption.des
        }else{
          delete standards[i]
        }
      }
      if(formData.productType<4){
        formData.stock=1
      }
      let params = {
        seckillProductId: id,
        ...pick(formData, ['detail', 'area', 'productType', 'propertyType', 'seckillPrice','originalPrice', 'initPrice', 'grads', 'securityMoney', 'earnestMoney', 'squarePrice', 'orientation', 'imageUrls', 'tags', 'salePrice', 'consultantMobile', 'realtyConsultant', 'productLabel', 'projectId','productBankAccountId','productDesc','promotionDetail','stock','enrollType','name','bankAccount','needEnroll','payWay','merchantCode']),
        imageUrls,
        ...standards,
      }
      // 商品类型非房源，不用传户型和户型朝向
      if(formData.productType==1){
        params.houseTypeName=formData.houseTypeName[0]+'室'+formData.houseTypeName[1]+'厅'+formData.houseTypeName[2]+'卫'
      }else{
        params.houseTypeName=''
        params.orientation=''
      }
      // formData.volume = selectOption.des


      // formData.weight = selectOption.des


      // formData.power = selectOption.des


      // formData.size = selectOption.des


      // formData.color = selectOption.des


      // formData.producingArea = selectOption.des

      // formData.other = selectOption.des
      accountType==1&&delete params.productBankAccountId
      const { success, msg, data } = yield call(update, { ...params })
      if (success) {
        message.success('操作成功', 1, () => {
          // yield put({type: 'queryInfo', payload: {}})
          let urlArray = MODULE_TO_ROUTES[tmpModule.namespace].urlArray
          console.log('urlArray', urlArray)
          AppBus.emit('closeTab', {
            key: urlArray[0],
            cbf: () => {
              hashHistory.push(urlArray[1])
              payload.resetFields()
            }
          })
        })
      }
    },

    // 新增 projectId,houseTypeName,detail,area,,productType,propertyType,initPrice,grads,securityMoney,earnestMoney,squarePrice,orientation,imageUrls,tags
    * create({ payload }, { put, select, call }) {
      let { id, formData, tags, imageUrls,standards,teamsOptions,selectOption,accountType } = yield select(state => state[tmpModule.namespace])
      yield put({ type: 'updateStore', payload: { btnLoading:true } })
      for(let i in standards){
        if(selectOption.value==i){
          standards[i]=selectOption.des
        }else{
          delete standards[i]
        }
      }
      if(formData.productType<4){
        formData.stock=1
      }
      let params = {
        ...pick(formData, ['detail', 'area', 'productType', 'propertyType', 'seckillPrice','originalPrice', 'initPrice', 'grads', 'securityMoney', 'earnestMoney', 'squarePrice', 'orientation', 'imageUrls', 'tags', 'salePrice', 'consultantMobile', 'realtyConsultant', 'productLabel', 'projectId','productBankAccountId','productDesc','promotionDetail','enrollType','stock','bankAccount','needEnroll','payWay','merchantCode']),
        imageUrls,
        ...standards,
      }
      // 商品类型非房源，不用传户型和户型朝向
      if(formData.productType==1){
        params.houseTypeName=formData.houseTypeName[0]+'室'+formData.houseTypeName[1]+'厅'+formData.houseTypeName[2]+'卫'
      }else{
        params.houseTypeName=''
        params.orientation=''
      }
      accountType==1&&delete params.productBankAccountId
      const { success, msg, data } = yield call(create, { ...params })
      if (success) {
        message.success('操作成功', 1, () => {
          // yield put({type: 'queryInfo', payload: {}})
          let urlArray = MODULE_TO_ROUTES[tmpModule.namespace].urlArray
          console.log('urlArray', urlArray)
          AppBus.emit('closeTab', {
            key: urlArray[0],
            cbf: () => {
              hashHistory.push(urlArray[1])
              payload.resetFields()
            }
          })
        })
      }else{
        yield put({ type: 'updateStore', payload: { btnLoading:false } })
      }
    },

    // 获取区域地址
    * getArea({ payload }, { put, call, select }) {
      try {
        const { success, data } = yield call(areAddressGet)
        if (success) {
          //todo: 接口格式调整后删除
          let arr = [data[0]]
          data[0] = {
            label: '北京',
            value: '110100',
            children: arr
          }
          //去掉第三级，
          for (var i = 0; i < 33; i++) {
            for (var j = 0; j < data[i].children.length; j++) {
              delete data[i].children[j].children
            }
          }
          yield put({ type: 'updateStore', payload: { allAddress: data } })
        }
      } catch (e) {
        console.log(e)
      }
    },
    // 获取户型项目
    *houseListGet({ payload }, { put, call, select }) {
      try {
        const { success, rows } = yield call(houseListGet, { ...payload, pageSize: 10000 })
        if (success) {
          let list=rows||[]
          let arr=[]
          list.map((item,index)=>{
            arr.push({ label: item.name||'', value: item.productId+''||'' })
          })
          yield put({ type: 'updateStore', payload: { houseList: arr || [] } })
        }
      } catch (e) {
        console.log(e)
      }
    },
    // 标签列表
    * getLabelQueryList({ payload }, { put, call, select }) {
      try {
        const { rows } = yield call(labelQueryList, {type:5})
        yield put({ type: 'updateStore', payload: { tagsList: rows } })
      } catch (e) {
        console.log(e)
      }
    },
    // 对公账户
    * queryAccount({ payload }, { put, call, select }) {
      let { formData,id }=payload
      // let { formData }=yield select(state => state[tmpModule.namespace])
      try {
        const {success, msg, data=[], } = yield call(queryAccount,id)
        if(success){
          if(formData && formData.productBankAccountId){
            data.map((item,index)=>{
              if(formData.productBankAccountId===item.productBankAccountId){
                formData.bankAccount=data[index].bankAccount      
               }
            })
            }
        }
        yield put({ type: 'updateStore', payload: { accountList: data,} })
      } catch (e) {
        console.log(e)
      }
    },

    * gethouseTypeList({ payload }, { put, call, select }) {
      try {
        let params = {
          pageNo: 1,
          pageSize: 1000,
          ...payload
        }
        const { success, msg, rows } = yield call(gethouseTypeList, { ...params })
        let list = []
        yield put({ type: 'updateStore', payload: { houseTypeList: rows || [] } })

      } catch (e) {
      }
    },
  },
  // 存入状态机
  reducers: {
    updateStore(preState, action) {
      return Object.assign({}, preState, action.payload)
    },
  }
}

export default tmpModule
